package pl.edu.pw.ee.buildcity.scheduler.listeners;

import org.apache.commons.lang.time.FastDateFormat;
import org.apache.log4j.Logger;
import org.quartz.*;
import pl.edu.pw.ee.buildcity.commons.Const;
import pl.edu.pw.ee.buildcity.entities.BuildDefinition;
import pl.edu.pw.ee.buildcity.scheduler.BuildContext;
import pl.edu.pw.ee.buildcity.services.BuildDefinitionService;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author mgrzechocinski
 * @since 2009-10-18
 */
public class BuildJobExecutionListener implements JobListener {

	public static final String LISTENER_NAME = "buildJobExecutionListener";

	private static final Logger log = Logger.getLogger(BuildJobExecutionListener.class);

	private final FastDateFormat fdf = FastDateFormat.getInstance("yyyy/MM/dd HH:mm:ss,sss");

	@Resource(name = "buildDefinitionService")
	private BuildDefinitionService buildDefinitionService;

	@Override
	public String getName() {
		return LISTENER_NAME;
	}

	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
	}

	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
		String jobName = context.getJobDetail().getName();

		BuildContext buildContext = createBuildContext(jobName);
		context.put(Const.JOB_CONTEXT_KEY_BUILD_CONTEXT, buildContext);

		String executionReason = resolveExecutionReason(context);
		log.info("BuildActivity " + jobName + " is about to be executed at " + fireTime(context) + ". Reason: " + executionReason);
	}

	private String resolveExecutionReason(JobExecutionContext context) {
		Trigger trigger = context.getTrigger();
		String executionReason = "fired manually";
		if (trigger instanceof CronTrigger) {
			executionReason = "by cron: " + ((CronTrigger) trigger).getCronExpression();
		}
		return executionReason;
	}

	private BuildContext createBuildContext(String jobName) {
		BuildDefinition buildDefinition = buildDefinitionService.getByName(jobName);
		BuildContext buildContext = new BuildContext(buildDefinition);
		return buildContext;
	}

	@Override
	public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
		String jobName = context.getJobDetail().getName();
		log.info("Build of " + jobName + " ended! Start: " + fireTime(context) + ", end:" + endTime() + ", took [ms]: "
				+ context.getJobRunTime());
	}

	private String fireTime(JobExecutionContext context) {
		return fdf.format(context.getFireTime());
	}

	private String endTime() {
		return fdf.format(new Date());
	}

}